package com.example.springblog.controller;


import com.example.springblog.constants.Constant;
import com.example.springblog.model.BlogInfo;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.BlogService;
import com.example.springblog.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RequestMapping("/blog")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;

    @RequestMapping("/getBlogList")
    public List<BlogInfo> getBlogList(HttpServletRequest request) {
        return blogService.getBlogList();
    }

    @RequestMapping("/getBlogDetail")
    public BlogInfo getBlogDetail(Integer blogId) {
        System.out.println(666);
        if (blogId == null || blogId < 0) return null;
        BlogInfo blogInfo = blogService.getBlogDetail(blogId);
        System.out.println(666);
        return blogInfo;
    }

    @RequestMapping("publishBlog")
    public Result publishBlog(HttpServletRequest request,String title,String content) {
        String token = request.getHeader(Constant.USER_TOKEN_HEADER);
        Integer userId = JwtUtils.getUserInfoFromToken(token);
        if (userId == null || userId < 0) return Result.fail("用户未登录");
        if (title == null || content == null) {
            return Result.fail("文章标题或者内容为空");
        }
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogInfo.setUserId(userId);
        blogService.addBlog(blogInfo);
        return Result.success(true);
    }
}
